const db = require('../config/db');

const createOrder = async (userId, items, totalAmount, address) => {
  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();
    
    // 创建订单
    const [orderResult] = await conn.query(
      'INSERT INTO orders (user_id, total_amount, status, address) VALUES (?, ?, ?, ?)',
      [userId, totalAmount, 'pending', address]
    );
    const orderId = orderResult.insertId;
    
    // 添加订单项
    for (const item of items) {
      await conn.query(
        'INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)',
        [orderId, item.product_id, item.quantity, item.price]
      );
    }
    
    // 清空购物车
    await conn.query('DELETE FROM cart WHERE user_id = ?', [userId]);
    
    await conn.commit();
    
    return orderId;
  } catch (err) {
    await conn.rollback();
    throw err;
  } finally {
    conn.release();
  }
};

const getOrdersByUserId = async (userId) => {
  const [orders] = await db.query(`
    SELECT o.*, 
      (SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.id) as item_count
    FROM orders o
    WHERE o.user_id = ?
    ORDER BY o.created_at DESC
  `, [userId]);
  
  return orders;
};

const getOrderDetails = async (orderId, userId) => {
  const [order] = await db.query(`
    SELECT o.* FROM orders o 
    WHERE o.id = ? AND o.user_id = ?
  `, [orderId, userId]);
  
  if (!order[0]) return null;
  
  const [items] = await db.query(`
    SELECT oi.*, p.name, p.image 
    FROM order_items oi
    JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = ?
  `, [orderId]);
  
  return {
    ...order[0],
    items
  };
};

module.exports = {
  createOrder,
  getOrdersByUserId,
  getOrderDetails
};